package cn.xetsoft.supermarket.view;

import cn.xetsoft.supermarket.common.DataResponse;
import cn.xetsoft.supermarket.common.Role;
import cn.xetsoft.supermarket.common.SystemData;
import cn.xetsoft.supermarket.dao.impl.UserDaoImpl;
import cn.xetsoft.supermarket.entity.User;
import cn.xetsoft.supermarket.service.Bean;
import cn.xetsoft.supermarket.service.UserService;
import cn.xetsoft.supermarket.service.impl.UserServiceImpl;
import cn.xetsoft.supermarket.util.PropertiesUtil;
import org.apache.commons.codec.digest.DigestUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * 登录页面
 */
public class LoginFrame extends JFrame {
    private UserService userService = Bean.getUserServiceInstance();

    //对页面进行调色
    Color mainPaneColor = new Color(230, 230, 250);
    Color mainFrameColor = new Color(186, 110 ,64);
    Color logoFramColor = new Color(186, 110, 64);
    JLayeredPane layeredPane = new JLayeredPane();  // 面板层
    ImageIcon lgImage ;//Logo层
    JPanel bgPanel = new JPanel(); // 背景面板
    JPanel mainPanel = new JPanel(); // 登陆面板
    JPanel logoPanel  = new JPanel();//企业logo
    //门店label
    final JLabel server_ip = new  JLabel("门店:");
    //用户名label
    final JLabel user_name = new JLabel("用户名:");
    //密码label
    final JLabel user_password = new JLabel("密   码:");
    //登入按钮
    JButton button_ok = new JButton("登陆");// 确认按钮
    //注册按钮
    JButton button_Register = new JButton("注册");// 确认按钮
    //取消按钮
    JButton button_cansel = new JButton("取消");//取消按钮
    JComboBox text_ip   = null;//服务器IP和端口号
    JTextField text_name = new JTextField();          // 登陆用户名
    JPasswordField text_password = new JPasswordField();    // 登陆密码

    private static final long serialVersionUID = 1L;
    // 用于处理拖动事件，表示鼠标按下时的坐标，相对于JFrame
    int xOld = 0;
    int yOld = 0;


    //构造方法
    public LoginFrame() {
        super();
        initialize();
        addListener(this);
    }

    //初始化页面,将控件添加到页面上
    public void initialize() {
        this.setTitle("登入 - 熵客云超市管理");
        this.setLayout(null);
        // 处理拖动事件
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                xOld = e.getX();
                yOld = e.getY();
            }
        });
        this.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                int xOnScreen = e.getXOnScreen();
                int yOnScreen = e.getYOnScreen();

                int xx = xOnScreen - xOld;
                int yy = yOnScreen - yOld;
                LoginFrame.this.setLocation(xx, yy);
            }
        });



        layeredPane.setBounds(0, 0, 600, 600);
        this.add(layeredPane);

        // 背景Panel
        bgPanel.setBounds(0, 0, 600, 600);
        layeredPane.add(bgPanel, new Integer(Integer.MIN_VALUE));


        //logo界面， 传播企业文化
        logoPanel.setBounds(0, 0,  170,  170);
        logoPanel.setLayout(null);
        logoPanel.setBackground(Color.WHITE);
        logoPanel.setBorder(BorderFactory.createTitledBorder(""));
        logoPanel.setBorder(BorderFactory.createLineBorder(logoFramColor));
        layeredPane.add(logoPanel);
        /**
         * 得到路径区别开发环境和jar包
         */
        String imgFile = "Images/Logo.png";
        if (!PropertiesUtil.getProperty("debug.resources.type").equals("jar")){
            imgFile = Class.class.getResource("/").getPath() + imgFile;
        }
        lgImage = new ImageIcon(imgFile);
        JLabel logo = new JLabel(change(lgImage,1.1));

        logoPanel.add(logo);
        logo.setBounds(new Rectangle(0, 0,  170,  170));



        // 主界面，登陆界面，包含服务器ip，用户名，密码等

        mainPanel.setBounds(150, 0, 350, 170);
        mainPanel.setLayout(null);
        mainPanel.setBackground(mainPaneColor);
        mainPanel.setBorder(BorderFactory.createTitledBorder(""));
        mainPanel.setBorder(BorderFactory.createLineBorder(mainFrameColor));
        layeredPane.add(mainPanel);

        mainPanel.add(server_ip);
        server_ip.setBounds(new Rectangle(25, 40,  62,  25));
        server_ip.setFont(new Font("微软雅黑", 1, 14));


        mainPanel.add(user_name);
        user_name.setBounds(new Rectangle(25, 70, 62, 25));
        user_name.setFont(new Font("微软雅黑", 1, 14));


        mainPanel.add(user_password);
        user_password.setBounds(new Rectangle(25, 100, 62, 25));
        user_password.setFont(new Font("微软雅黑", 1, 14));


        String[] default_ip={"厦门店","福州店"};
        text_ip = new JComboBox(default_ip);
        mainPanel.add(text_ip);
        text_ip.setBounds(new Rectangle(95, 40, 240 , 25));
        text_ip.setFont(new Font("微软雅黑", 1, 12));
        text_ip.setEditable(true);

        mainPanel.add(text_name);
        text_name.setBounds(new Rectangle(95, 70, 240, 25));
        text_name.setFont(new Font("微软雅黑", 1, 12));

        mainPanel.add(text_password);
        text_password.setBounds(new Rectangle(95, 100, 240, 25));
        text_password.setFont(new Font("", Font.PLAIN, 20)); // 设置回显字符大小

        mainPanel.add(button_ok);
        button_ok.setBounds(new Rectangle(50, 130,  80, 25));
        button_ok.setFont(new Font("微软雅黑", 1, 12));

        mainPanel.add(button_Register);
        button_Register.setBounds(new Rectangle(155, 130,  80, 25));
        button_Register.setFont(new Font("微软雅黑", 1, 12));

        mainPanel.add(button_cansel);
        button_cansel.setBounds(new Rectangle(255, 130,  80, 25));
        button_cansel.setFont(new Font("微软雅黑", 1, 12));

        text_name.addFocusListener(new FocusAdapter() {
            /**
             * Invoked when a component gains the keyboard focus.
             *
             * @param e
             */
            @Override
            public void focusGained(FocusEvent e) {
                super.focusGained(e);
                text_name.setText("");
                text_password.setText("");
            }
        });

        //临时设置密码，方便调试
        if (PropertiesUtil.getProperty("debug.uop").equalsIgnoreCase("true")){
            text_name.setText("admin");
            text_password.setText("123456");
        }

        this.setBounds(0, 0, 500, 170);
        this.setUndecorated(true);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }

    //图片缩放
    public ImageIcon change(ImageIcon image,double i){//  i 为放缩的倍数

        int width=(int) (image.getIconWidth()*i);
        int height=(int) (image.getIconHeight()*i);
        Image img=image.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT);
        ImageIcon image2=new ImageIcon(img);

        return image2;

    }

    //添加监听事件
    private void addListener(LoginFrame loginFrame){
        button_ok.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取页面数据,到数据库内进行匹配登录
                String username = loginFrame.text_name.getText();
                String pass = String.valueOf(loginFrame.text_password.getPassword());
                //调用登入服务，得到数据代理类
                DataResponse<User> userDataResponse = userService.login(username,pass);
                if (userDataResponse.isSuccess()){//成功，显示结果数据
                    System.out.println(userDataResponse.getData());
                    SystemData.setUser(userDataResponse.getData()); // 登入成功后，将用户信息放入全局静态类中
                    new FuncionFrame(text_ip.getSelectedItem().toString());
                    loginFrame.setVisible(false);
                } else { //失败查看错误信息
                    String msg = userDataResponse.getMsg();
                    JOptionPane.showMessageDialog(loginFrame, msg, "登录出错",JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        //注册页面跳转
        button_Register.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new RegisterFrame();
                loginFrame.setVisible(false);
            }
        });
        //退出
        button_cansel.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                loginFrame.setVisible(false);
            }
        });
    }
}